package com.gsq.zjcgj.base;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.gsq.zjcgj.ProjectApp;
import com.gsq.zjcgj.R;
import com.gsq.zjcgj.dialog.LoadingDialog;
import com.gsq.zjcgj.handler.CrashHandler;
import com.gy.mbaselibrary.App;
import com.gy.mbaselibrary.base.BaseActivity;
import com.gy.mbaselibrary.inters.IKeyBoardVisibleListener;
import com.gy.mbaselibrary.utils.ScreenUtil;
import com.gy.mbaselibrary.utils.ToastUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 创建者：高业
 * 时间：2018/2/6
 * 类描述：项目activity的基类，项目activity里的公共方法在这里里面
 * 修改人：
 * 修改时间：2018/2/6
 * 修改备注：
 */

public abstract class ProjectBaseActivity extends BaseActivity {
    //软键盘是否隐藏显示
    protected boolean isVisiableForLast = false;
    //当前的fragment
    private Fragment currentFragment;
    //fragment管理类
    private FragmentManager fragmentManager;
    //由于得登录后才能使用app，所以在每个activity创建的时候都把当前登录用户获取到，便于使用
    //protected UserBean user;

    private LoadingDialog loadingDialog;
    final static int COUNTS = 5;//点击次数
    final static long DURATION = 10000;//规定有效时间
    long[] mHits = new long[COUNTS];

    /*private ShengjiDialog shengjiDialog;
    private UserBean user;*/






    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!ProjectApp.getInstance().isDebug()){
            CrashHandler.getInstance().init(getCurrentContext());
        }

        /*if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            //boolean result = fixOrientation();
        }*/
     //   addOnSoftKeyBoardVisibleListener(this,null);
    }



    protected boolean isTranslucentOrFloating(){
        boolean isTranslucentOrFloating = false;
        try {
            int [] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean)m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }


    protected boolean fixOrientation(){
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo)field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void initUser() {
        //user = UserUtils.getUser(getCurrentContext());
    }

    //监听软键盘的显示和隐藏
    public void addOnSoftKeyBoardVisibleListener(Activity activity, final IKeyBoardVisibleListener listener) {
        final View decorView = activity.getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                //计算出可见屏幕的高度
                int displayHight = rect.bottom - rect.top;
                //获得屏幕整体的高度
                int hight = decorView.getHeight();
                int startBarHeight = ScreenUtil.getStatusBarHeight(getCurrentContext());
                int bottomBarHeight = ScreenUtil.getBottomStatusHeight(getCurrentContext());
                //获得键盘高度
                int keyboardHeight = hight - displayHight - startBarHeight - bottomBarHeight;
                //UserUtils.setKeybordheight(getCurrentContext(),keyboardHeight);
                boolean visible = (double) displayHight / hight < 0.8;
                if (visible != isVisiableForLast) {
                    if (listener != null)
                    listener.onSoftKeyBoardVisible(visible, keyboardHeight);
                }
                isVisiableForLast = visible;
            }
        });
    }



    //切换fragment
    protected void switchContent(Fragment to, int frId) {
        if (fragmentManager == null) {
            fragmentManager = getSupportFragmentManager();
        }
        if (to != null && to != currentFragment) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            if (currentFragment != null) {
                if (!to.isAdded()) {    // 先判断是否被add过
                    transaction.hide(currentFragment).add(frId, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
                } else {
                    transaction.hide(currentFragment).show(to).commit(); // 隐藏当前的fragment，显示下一个
                }
            } else {
                transaction.add(frId, to).commit();
            }
            currentFragment = to;
        }
    }


    //隐藏diolog
    public void hideNetDialog(){
        if (loadingDialog != null){
            if (loadingDialog.isShowing()){
                loadingDialog.dismiss();
            }
        }
    }


    //显示dialog
    public void showNetDialog(){
        showNetDialog(null,false);
    }

    //显示dialog
    public void showNetDialog(String str, boolean cantouch){
        if (loadingDialog == null){
            loadingDialog = new LoadingDialog(getCurrentContext(), R.style.netdialog_base);
        }
        loadingDialog.show(str);
        loadingDialog.setCancelable(cantouch);
        loadingDialog.setCanceledOnTouchOutside(cantouch);
    }

    //显示dialog
    public void showNetDialog(String str){
        showNetDialog(str,false);
    }


    @Override
    public <T> void success(int requestCode, String url, T baseBean, String response, Object tag, Map<String, Object> tagObj, Map<String, String> params, Map<String, String> headParams) {

    }

    @Override
    public void fail(int requestCode, String url, Exception e, Object tag, Map<String, Object> tagObj, Map<String, String> params, Map<String, String> headParams) {
        if (App.getInstance().isDebug()){
            ToastUtil.showToast(getCurrentContext(),e.toString() + " url:" + url);
        }
    }

}
